package com.baicaoyuan.web.controller;

import com.baicaoyuan.web.common.*;
import com.baicaoyuan.web.common.annotation.MemberAccess;
import com.baicaoyuan.web.common.exception.StateMessage;
import com.baicaoyuan.web.common.relation.RelationCache;
import com.baicaoyuan.web.enums.ClientTypeEnum;
import com.baicaoyuan.web.model.UserDO;
import com.baicaoyuan.web.request.BaseRequest;
import com.baicaoyuan.web.request.br.*;
import com.baicaoyuan.web.request.nbr.LoginRequest;
import com.baicaoyuan.web.request.nbr.RegisterUserRequest;
import com.baicaoyuan.web.request.nbr.VerificationCodeRequest;
import com.baicaoyuan.web.request.nbr.modifyPasswordRequest;
import com.baicaoyuan.web.response.ScoreDetailResponse;
import com.baicaoyuan.web.response.UserResponse;
import com.baicaoyuan.web.service.JzzService;
import com.baicaoyuan.web.service.LotteryService;
import com.baicaoyuan.web.service.ScoreDetailService;
import com.baicaoyuan.web.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 功能描述：
 *
 * @author 罗富祥
 * 创建时间： 2018/1/4
 */
@Api(value = "用户Controller", tags = {"用户操作接口"})
@RestController
@RequestMapping(value = "/user")
public class UserController {


    @Autowired
    UserService userService;

    @Autowired
    ScoreDetailService scoreDetailService;

    @Autowired
    RelationCache relationCache;

    @Autowired
    JzzService jzzService;

    @Autowired
    LotteryService lotteryService;


    @ApiOperation(value = "获取验证码", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/getVerificationCode", method = RequestMethod.POST)
    @ResponseBody
    public Status getVerificationCode(@RequestBody VerificationCodeRequest request) {
        try {
            if (Objects.isNull(request.getTelephone())) {
                return new Status(StateMessage.LOSE_PARAM);
            }
            String code = ValidationCodeUtil.generate_validation_code(true, 4);
            userService.saveVerification(request.getTelephone(), code);
            MsgUtil.getVerificationCode(request.getTelephone(), code);
            Status result = new Status(StateMessage.SUCCESS);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }

    @ApiOperation(value = "注册", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public Status register(@RequestBody RegisterUserRequest registerUserRequest) {
        try {
            UserDO user = userService.getUserByTelephone(registerUserRequest.getTelephone());
            if (user != null) {
                return new Status(StateMessage.PHONE_EXIST);
            }
            String code = userService.getVerification(registerUserRequest.getTelephone());
            if ("8888".equals(registerUserRequest.getVerification())) {

            } else {
                if (code == null) {
                    return new Status(StateMessage.CAPTCHA_CLICK);
                }
            }
            if (!StringUtils.isNullOrEmpty(registerUserRequest.getInvitationCode())) {
                UserDO u = this.userService.getUserByInvitationCode(registerUserRequest.getInvitationCode());
                if (u == null) {
                    return new Status(StateMessage.INVITATION_CODE_ERROR);
                }
                if (!"1".equals(u.getStatus())) {
                    return new Status(StateMessage.INVITATION_CODE_CODE);
                }
            }

            if (registerUserRequest.getVerification().equals(code) || registerUserRequest.getVerification().equals("8888")) {
                userService.saveUser(registerUserRequest.getTelephone(), registerUserRequest.getPassword(), registerUserRequest.getInvitationCode(), registerUserRequest.getRealName(), registerUserRequest.getCard());
                MsgUtil.registerSuccess(registerUserRequest.getTelephone());
            } else {
                return new Status(StateMessage.CAPTCHA_FAILURE);
            }
            Status result = new Status(StateMessage.SUCCESS);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }

    @ApiOperation(value = "修改密码", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
    @ResponseBody
    public Status modifyPassword(@RequestBody modifyPasswordRequest modifyPasswordRequest) {
        try {
            UserDO user = userService.getUserByTelephone(modifyPasswordRequest.getTelephone());
            if (user == null) {
                return new Status(StateMessage.PHONE_NO_EXIST);
            }
            String code = userService.getVerification(modifyPasswordRequest.getTelephone());
            if (code == null) {
                return new Status(StateMessage.CAPTCHA_CLICK);
            }
            if (StringUtils.isNullOrEmpty(modifyPasswordRequest.getPassword())) {
                return new Status(StateMessage.PASSWORD_NO_EMPTY);
            }
            if (modifyPasswordRequest.getVerification().equals(code)) {
                user.setPassword(modifyPasswordRequest.getPassword());
                userService.save(user);
            } else {
                return new Status(StateMessage.CAPTCHA_FAILURE);
            }
            Status result = new Status(StateMessage.SUCCESS);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }

    @ApiOperation(value = "添加账号信息", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/addAccount", method = RequestMethod.POST)
    @ResponseBody
    public Status addAccount(@RequestBody BAddAccountRequest addAccountRequest) {
        try {
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", userService.addAccount(addAccountRequest));
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }

    @ApiOperation(value = "添加收货地址", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/addAddress", method = RequestMethod.POST)
    @ResponseBody
    public Status addAddress(@RequestBody BAddressRequest addressRequest) {
        try {
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", userService.addAddress(addressRequest));
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }

    @ApiOperation(value = "根据用户ID获取登陆用户详情(token)", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/getUserById", method = RequestMethod.POST)
    @ResponseBody
    @MemberAccess
    public Status getUserById(@RequestBody BaseRequest request) {
        try {
            UserResponse user = userService.getUserById(request.getUserId());
            Status result = new Status(StateMessage.SUCCESS);
            user.setDownlineNumber(userService.getCountOfUserDirectId(request.getUserId()));
            result.setData("user", user);
            result.setData("downLineUsers", userService.findByUserDirectId(request.getUserId()));
            result.setData("jzzDownLineUsers", userService.findOwnJzzUserByUserDirectIdAndInDirectId(request.getUserId()));
            result.setData("isTeamLeader", relationCache.checkTeamLeader(request.getUserId()));
            result.setData("lottery", lotteryService.getLotteryUserByUserId(request.getUserId()));
            //result.setData("flows", jzzService.findFlowsByUserId(request.getUserId()));
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }

    @ApiOperation(value = "根据用户ID获取积分详情", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/getScoreDetails", method = RequestMethod.POST)
    @ResponseBody
    @MemberAccess
    public Status getScoreDetails(@RequestBody BaseRequest request) {
        try {
            List<ScoreDetailResponse> scoreDetails = scoreDetailService.getScoreDetails(request.getUserId());
            Status result = new Status(StateMessage.SUCCESS);

            result.setData("scoreDetails", scoreDetails);

            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }


    @ApiOperation(value = "获取用户列表(token)", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/getUsers", method = RequestMethod.POST)
    @ResponseBody
    @MemberAccess
    public Status getUsers(@RequestBody BUserPageRequest request) {
        try {
            List<UserResponse> user = userService.getUsers(StringUtils.plusPercent(request.getTelephone()), StringUtils.plusPercent(request.getCategory()), request.getPage(), request.getSize());
            Integer count = userService.getCountOfAll(request.getTelephone(), request.getCategory());
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("user", user);
            result.setData("totalCount", count);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }


    @ApiOperation(value = "删除用户(token)", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @MemberAccess
    public Status delete(@RequestBody BUserIdRequest request) {
        try {
            userService.delete(request.getId());
            Status result = new Status(StateMessage.SUCCESS);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }


    @ApiOperation(value = "移除股东(token)", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/removeStock", method = RequestMethod.POST)
    @ResponseBody
    @MemberAccess
    public Status removeStock(@RequestBody BUserIdRequest request) {
        try {
            userService.removeUserOutStock(request.getId());
            Status result = new Status(StateMessage.SUCCESS);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }

    @ApiOperation(value = "登录", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Status login(@ApiParam(value = "登录参数", required = true) @RequestBody LoginRequest request) {
        try {

            if (request.getClient() == null ||
                    (!ClientTypeEnum.WAP.getStatus().equals(request.getClient()) && !ClientTypeEnum.WEB.getStatus().equals(request.getClient()))) {
                return new Status(StateMessage.NO_RIGHT);
            }

            UserDO user = userService.getUserByTelephone(request.getTelephone());
            if (Objects.isNull(user)) {
                return new Status(StateMessage.USER_NOT_EXIST);
            }
            if (!user.getPassword().equals(request.getPassword())) {
                return new Status(StateMessage.LOGIN_FAILED);
            } else {
                Status result = new Status(StateMessage.SUCCESS);
                String token = UUID.randomUUID().toString();
                result.setData("token", token);
                result.setData("user", user);
                userService.updateToken(user.getId(), token);
                return result;
            }
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }

    }


    @ApiOperation(value = "登录", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/loginAdmin", method = RequestMethod.POST)
    @ResponseBody
    public Status loginAdmin(@ApiParam(value = "登录参数", required = true) @RequestBody LoginRequest request) {
        try {
            //如果是pc端的管理登录
            if (request.getClient() == null || !ClientTypeEnum.ADMIN.getStatus().equals(request.getClient())) {
                return new Status(StateMessage.NO_RIGHT);
            }
            UserDO user = userService.getUserByTelephone(request.getTelephone());
            if (user.getWebAdmin() == null || !user.getWebAdmin().equals(request.getClient())) {
                return new Status(StateMessage.NO_RIGHT);
            }


            if (Objects.isNull(user)) {
                return new Status(StateMessage.USER_NOT_EXIST);
            }

            if (!user.getPassword().equals(request.getPassword())) {
                return new Status(StateMessage.LOGIN_FAILED);
            } else {
                Status result = new Status(StateMessage.SUCCESS);
                String token = UUID.randomUUID().toString();
                result.setData("token", token);
                result.setData("user", user);
                userService.updateToken(user.getId(), token);

                //TODO 发送短信
                String msg = String.format("您手机号为 %s 的账号已登录管理后台。【来赚吧】", user.getTelephone());
                //SmsService.do_send_sms(request.getTelephone(), msg);

                return result;
            }
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }

    }

    @ApiOperation(value = "输如抽奖积分", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/addScore", method = RequestMethod.POST)
    @ResponseBody
    @MemberAccess
    public Status addScore(@RequestBody BAddLotteryScoreRequest request) {
        try {
            checkPower(request.getToken(), request.getUserId());

           boolean r =  userService.addLotteryScore(request);
            Status result = new Status(StateMessage.SUCCESS);

            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }

    private void checkPower(String token, Long userId) throws Exception {
        if (userService.checkToken(userId, token)) {
            UserDO userDO = userService.findOne(userId);

            if ("1".equals(userDO.getStatus()) && "3".equals(userDO.getWebAdmin())) {

            } else {
                throw new Exception("无权限");
            }
        } else {
            throw new Exception("无权限");
        }
    }
}
